import {
  CameraControls,
  MeshReflectorMaterial,
} from '@react-three/drei';
import { useFrame, useThree } from '@react-three/fiber';
import { useEffect, useRef } from 'react';
import TWEEN from 'tween';
import { useSnapshot } from 'valtio';
import CameraControlsContext from '../context/CameraControlsContext';
import Computer from '../models/Computer';
import messageEvent from '../proxy/messageEvent';

const World = () => {
  const cameraControlsRef = useRef();
  const roomRef = useRef();
  const floorRef = useRef();
  const newMessageEvent = useSnapshot(messageEvent);

  useFrame(() => {
    TWEEN.update();
  });

  useEffect(() => {
    const newlist = messageEvent.cameraLookAt
    cameraControlsRef.current.setLookAt(newlist[0], newlist[1], newlist[2], newlist[3], newlist[4], newlist[5], true);
  }, [messageEvent.cameraLookAt]);
  return (
    <>
      <CameraControls
        ref={cameraControlsRef}
        infinityDolly={true}
        dollyToCursor={true}
        minPolarAngle={0} maxPolarAngle={Math.PI / 1.9}
      ></CameraControls>
      <CameraControlsContext.Provider value={cameraControlsRef}>
        <mesh
          ref={floorRef}
          position={[0, -1.5, 0]}
          rotation={[-Math.PI / 2, 0, 0]}
        >
          <planeGeometry args={[1000, 1000]} />
          <MeshReflectorMaterial
            blur={[300, 100]}
            resolution={1024}
            mixBlur={1}
            mixStrength={9}
            depthScale={1}
            minDepthThreshold={0.65}
            color="#2b2b2b"
            metalness={0.6}
            roughness={1}
          />
        </mesh>
        <Computer ref={roomRef} />
      </CameraControlsContext.Provider>
      <ambientLight intensity={1} />
      <directionalLight position={[0, 5, 2]} />
      <directionalLight position={[4, 5, -3]} />
    </>
  );
};

export default World;
